package com.meessiom.train.crm.reimburse.service;

import com.meessiom.train.crm.common.exception.ResourceNotFoundException;
import com.meessiom.train.crm.reimburse.model.Reimburse;
import com.meessiom.train.crm.reimburse.repository.ReimburseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ReimburseService {
    @Autowired
    private ReimburseRepository reimburseRepository;


    public void deleteReimburse(long id) {
        Reimburse reimburse = reimburseRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Reimburse not exist with id" + id));

        reimburseRepository.delete(reimburse);
    }

    public List<Reimburse> getAllReimburses(Long id, String reimburseState, String reimburseName,
                                            String reimburseDepartment, Date reimburseDate) {
        Specification<Reimburse> spec = Specification.where(null);

        if (id != null) {
            spec = spec.and((root, query, cb) ->
                    cb.equal(root.get("id"), id));
        }

        if (reimburseName != null && !reimburseName.isEmpty()) {
            spec = spec.and((root, query, cb) ->
                    cb.like(root.get("reimburseName"), "%" + reimburseName + "%"));
        }

        if (reimburseDepartment != null && !reimburseDepartment.isEmpty()) {
            spec = spec.and((root, query, cb) ->
                    cb.like(root.get("reimburseDepartment"), "%" + reimburseDepartment + "%"));
        }

        if (reimburseDate != null) {
            spec = spec.and((root, query, cb) -> {
                return cb.between(root.get("reimburseDate"),
                        reimburseDate,
                        new Date(reimburseDate.getTime() + 86400000)); // +1 day
            });
        }

        if (reimburseState != null && !reimburseState.isEmpty()) {
            spec = spec.and((root, query, cb) ->
                    cb.equal(root.get("reimburseState"), reimburseState));
        }

        return reimburseRepository.findAll(spec);
    }

    public Reimburse createReimburse(Reimburse reimburse) {
        return reimburseRepository.save(reimburse);
    }
}
